package com.apes.autoparts.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.product.model.SupplierCodingRecord;
import com.apes.autoparts.product.repository.SupplierCodingRecordRespository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SupplierCodingRecordService {

    @Autowired
    private SupplierCodingRecordRespository supplierCodingRecordRespository;

    /**
     * 保存译码返回结果
     * @param request
     */
    public List<SupplierCodingRecord> supplierCodingRecordInsert(SimpleRequest request){
        List<SupplierCodingRecord> list = new ArrayList<>();
        JSONObject jo = request.getJO();
        JSONArray modelArray = jo.getJSONArray("model");
        modelArray.stream().forEach(m ->{
            JSONObject jsonObject = (JSONObject) m;
            SupplierCodingRecord supplierCodingRecord = new SupplierCodingRecord();
            supplierCodingRecord.setBrandName(jo.getString("brandName"));
            supplierCodingRecord.setCartypeids(jsonObject.getString("carTypeId"));
            if(jsonObject.getJSONObject("partsInfos")!=null){
                supplierCodingRecord.setEpcPartsName(jsonObject.getJSONObject("partsInfos").getString("epcPartsName"));
                supplierCodingRecord.setInstallnum(jsonObject.getJSONObject("partsInfos").getString("installNum"));
                supplierCodingRecord.setRemark(jsonObject.getJSONObject("partsInfos").getString("remark"));
            }
            supplierCodingRecord.setPartsCode(jsonObject.getString("partsCodes"));
            supplierCodingRecord.setPartsNames(jsonObject.getString("partsName"));
            supplierCodingRecord.setStandardName(jsonObject.getString("standardName"));
            supplierCodingRecord.setVinAnalyseSource(jo.getString("vinAnalyseSource"));
            supplierCodingRecord.setVINCode(jo.getString("vinCode"));
            list.add(supplierCodingRecordRespository.saveAndFlush(supplierCodingRecord));
        });
        return list;
    }
}
